/**
 * Created by wenwang on 2017/8/23.
 */
const path = require('path')
const fs = require('fs')

function WebpackInlineJsPlugin(options) {
  // Configure your plugin with options...
  this.options = options;
}

WebpackInlineJsPlugin.prototype.apply = function (compiler) {
  compiler.plugin("done", function (stats) {
    console.log("The done...");
    let {
      compilation: {
        options:{
          entry,
          output:{path: thepath}
        }
      }
    } = stats
    let keys = Object.keys(entry);
    console.log('目标路径:', thepath);
    keys.forEach(it => {
      let fullPath = path.resolve(thepath, './' + it)
      let jsfullPath = fullPath + '.js'
      let htfullPath = fullPath + '.html'
      if (fs.existsSync(jsfullPath) && fs.existsSync(htfullPath)) {
        console.log('目标文件:', htfullPath);
        let jstext = fs.readFileSync(jsfullPath, {encoding: 'utf-8'})
        let httext = fs.readFileSync(htfullPath, {encoding: 'utf-8'})
        let mepos = httext.indexOf('<script data-me>')
        let bodypos = httext.indexOf('</body>')
        let first, secand
        if (mepos !== -1) {
          first = httext.substr(0, mepos).trim()
        }
        else {
          first = httext.substr(0, bodypos).trim()
        }
        secand = httext.substr(bodypos).trim()
        let html = first + '\n<script data-me>' + jstext + '<\/script>' + secand
        fs.writeFileSync(htfullPath, html)
        fs.unlinkSync(jsfullPath)
      }
    })

  })
}

module.exports = WebpackInlineJsPlugin

